package com.wenhao.lock;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author Wenhao Tong
 * @create 2021-08-20 22:36
 */
public class MyLockDemo {

    public static void main(String[] args) {
        Phone phone = new Phone();

        for (int i = 0;i < 10;i++) {
            new Thread(() -> {
                phone.myLock();
                try {
                    phone.sell();
                } finally {
                    phone.myUnlock();
                }
            },String.valueOf(i)).start();
        }
    }

}

class Phone {

    private AtomicStampedReference<Thread> lock = new AtomicStampedReference<>(null,1);

    void myLock () {
        int stamp = lock.getStamp();
        while (lock.compareAndSet(null,Thread.currentThread(),stamp,stamp + 1)) {

        }
    }

    void myUnlock () {
        int stamp = lock.getStamp();
        lock.compareAndSet(Thread.currentThread(),null,stamp,stamp + 1);
    }

    int count = 10;

    public void sell() {
        count--;
        System.out.println(Thread.currentThread().getName() + " " + count);
    }
}


